<?php
namespace Home\Controller;
class MycreditController extends HomeBaseController
{
    
    /**
     * 查询借款信息
     *
     */
    public function myloaderinfo(){
        $loaderInfolist = M('LoaderInfo')->where('uid='.session('uid'))->order('create_time desc')->select();
        $this->assign('investlist',$loaderInfolist);
        $this->display('credit/myloaderInfo');
    }
    /*
     * 查询投资信息
     */
    public function myinvestorinfo(){
        
        $InvestorInfodao= M('InvestorInfo');
        $condi['dd_user_assets.creditmoney']=array('gt',100);
        $condi['dd_user_assets.uid']=session('uid');
        $investlist = $InvestorInfodao
        ->join(' LEFT JOIN dd_user_assets on dd_investor_info.uid=dd_user_assets.uid')
        ->join(' LEFT JOIN dd_inves_domcate on dd_investor_info.id=dd_inves_domcate.inve_id')
        ->field('dd_investor_info.id,dd_investor_info.term_begin,dd_investor_info.create_time,dd_investor_info.term_end,SUM(dd_investor_info.tovalue) as tovalue,dd_inves_domcate.id as invesid,dd_inves_domcate.is_open,dd_inves_domcate.rate,dd_inves_domcate.domtypname,dd_inves_domcate.credit,dd_user_assets.creditmoney as money')
        ->where($condi)
        ->group('dd_investor_info.id,dd_inves_domcate.domtypeid')->order("dd_investor_info.create_time desc")->select();
        $this->assign('investlist',$investlist);
        $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.session('uid'))->select();
        $this->assign('creditmoney',$creditmoney[0]['creditmoney']);
        $summoney=M('CredFlow')->where('investuid='.session('uid'))->sum('money');
        if(empty($summoney)){
            $summoney=0;
        }
        $this->assign('summoney',$summoney);
        $interestall=M('CredFlow')->where('investuid='.session('uid').' and status=2')->sum('persionnum*interest');
        if(empty($interestall)){
            $interestall=0;
        }
        $this->assign('interestall',$interestall);
        $this->display('credit/myinvestorinfo');
    }
    
    public function loader(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $cond['uid']=session('uid');
        $cond['check_status']=3;
        $cond['trans_status']=1;
        $cond['is_mortage']=1;
        
        $domainDao=M('UserDomains');
        $count=$domainDao->
        where($cond)->count();
        $catelist = M('DomainType')->field('id,name')->select();
        $this->assign('catelist',$catelist);
        $this->assign('count',$count);
        $this->display('credit/loader');
    }
    
    public function userdomaincredit(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $cateid=I('cateid','');
        $cond['uid']=session('uid');
        $cond['check_status']=3;
        $cond['trans_status']=1;
        $cond['is_mortage']=1;
        $cond['domain_typeid']=$cateid;
        $domainDao=M('UserDomains');
        $domlist=$domainDao->
        field('id,domain_typeid,domain')->where($cond)->select();
        $count=$domainDao->where($cond)->count();
        $this->ajaxReturn(array('count'=>$count,'info' => $domlist));//0错误，1成功
        exit();
    }
    
    public function insertloader(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $domainids = I('domainid','');
        if ($domainids=='') {
            $this->ajaxReturn(array('code'=>'error','info' => '抵押域名不能为空！'));//0错误，1成功
            exit();
        }
        $overtimestr=I('overtimestr','');
        is_numeric($overtimestr);
        if(!preg_match('/^\\d+$/',$overtimestr)) {
            $this->ajaxReturn(array('code'=>'error','info' => '过期时间错误'));//0错误，1成功
            exit();
        }
        if($overtimestr=='' || $overtimestr<=0){
            $this->ajaxReturn(array('code'=>'error','info' => '过期时间必须选择！'));//0错误，1成功
            exit();
        }
        $LoaderInfo = D("LoaderInfo"); // 实例化LoaderInfo对象
        if (!$LoaderInfo->create($_POST,1)){
            // 如果创建失败 表示验证没有通过 输出错误提示信息
            $this->ajaxReturn(array('code'=>'error','info' => $LoaderInfo->getError()));//0错误，1成功
            exit();
        }
        $credmoney = I('credmoney','');
        if($credmoney<=0){
            $this->ajaxReturn(array('code'=>'error','info' => '授信额度必须大于0'));//0错误，1成功
            exit();
        }
        $rate = I('rate','');
        if($rate<=0 || $rate>25){
            $this->ajaxReturn(array('code'=>'error','info' => '借款利率必须小于等于25%'));//0错误，1成功
            exit();
        }
        $i=0;
        $where['uid']=session('uid');
        $where['is_mortage']=1;
        $where['check_status']=3;
        $where['trans_status']=1;
        $where['domain_typeid']=I('category','');
        $ddd='';
        $domainD=M('UserDomains');
        $domainArr=explode(',', $domainids);
        $rightDomArr=array();
        foreach ($domainArr as $domid){
            is_numeric($domid);
            if(!preg_match('/^\\d+$/',$domid)) {
                continue;
            }
            $where['id']=$domid;
            $result=$domainD->where($where)->setField(array('is_mortage'=>3));
            if($result!=false){
             $i=$i+1;   
             array_push($rightDomArr, $domid);
            }
        }
        $data['uid']=session('uid');
        $data['title']=I('title','');
        $money=$credmoney*count($rightDomArr);
        $data['money']=$money;
        $data['rate']=I('rate',0);
        $term=I('term','');
        if($term==0){
            $data['term']=I('termmonth',0);
            $data['tim_type']=2;
        }else{
            $data['term']=$term;
            $data['tim_type']=1;
        }
        $data['create_time']=date('y-m-d H:m:s',time());
        $data['descrp']=I('descrp','');
        $data['domainnum']=$i;
        $data['credmoney']=$credmoney;
        $data['number']=count($rightDomArr);
        $data['domaintypeid']=$where['domain_typeid'];
        $data['overtime']=date("Y-m-d",strtotime($overtimestr." day")).' 00:00:00';
        $data['cred_code']=D('CredFlow')->create_uuid();
        $loanid=$LoaderInfo->add($data);
        if($loanid!=null && $loanid>0){
            $loanDomain=M('LoanDomains');
            $loanData['loanid']=$loanid;
            foreach ($rightDomArr as $domid){
                $loanData['domainid']=$domid;
                $loanDomain->add($loanData);
            }
        }
        $resu=0;
        $resu=D('CredFlow')->zidongtoubiao($loanid,session('uid'),$data['cred_code']);
        if($resu==1){
            $this->ajaxReturn(array('code'=>'success','info' => '借款需求已通过自动匹配满标，请按期准时还款!'));//0错误，1成功
            exit();
        }else{
            $this->ajaxReturn(array('code'=>'success','info' => '借款需求发布成功!'));//0错误，1成功
            exit();
        }
    }
    
    public function investor(){
    
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
    
        $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.session('uid'))->select();
        $this->assign('creditmoney',$creditmoney[0]['creditmoney']);
        $domainTypelist = M('DomainType')->field('id,name')->order('id')->select();
        $this->assign('domainTypelist',$domainTypelist);
        $this->display('credit/investor');
    }
    
    public function insertinvestor(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.session('uid'))->select();
        if($creditmoney[0]['creditmoney']==0){
            $this->ajaxReturn(array('code'=>'error','info' => '您理财宝金额不足,请先充值理财宝！'));//0错误，1成功
            exit();
        }
        $morts = I('morts','');//1-23432,2-23423
        if ($morts=='') {
            $this->ajaxReturn(array('code'=>'error','info' => '授信类型不能为空！'));//0错误，1成功
            exit();
        }
        $mortsArr=explode(',', $morts);
        $mortsList=array();
        foreach ($mortsArr as $mor){
            if($mor==''){
                continue;
            }
            $creditAr=explode('-', $mor);
            if(empty($creditAr) || count($creditAr)<3){
                $this->ajaxReturn(array('code'=>'error','info' => '授信额度,利率必填！'));//0错误，1成功
                exit();
            }
            is_numeric($creditAr[0]);
            if(!preg_match('/^\\d+$/',$creditAr[0])  || $creditAr[0]<0) {
               $this->ajaxReturn(array('code'=>'error','info' => '授信域名类型有误！'));//0错误，1成功
                exit();
            }
            is_numeric($creditAr[1]);
            if(!preg_match('/^\\d+$/',$creditAr[1]) || $creditAr[1]<0) {
                $this->ajaxReturn(array('code'=>'error','info' => '授信额度输入有误,每个域名类型必须填入授信额度！'));//0错误，1成功
                exit();
            }
            is_numeric($creditAr[2]);
            if(!preg_match('/^\\d+$/',$creditAr[2]) || $creditAr[2]<0 || $creditAr[2]>25) {
                $this->ajaxReturn(array('code'=>'error','info' => '年利率输入有误！'));//0错误，1成功
                exit();
            }
            $domtype = M('DomainType')->field('name')->where('id='.$creditAr[0])->select();
            if(empty($domtype)){
                $this->ajaxReturn(array('code'=>'error','info' => '授信域名类型有误！'));//0错误，1成功
                exit();
            }
            $map=array(
              'domtypeid'=>$creditAr[0],
              'credit'=>$creditAr[1],
              'rate'=>$creditAr[2],
               'domtypname'=>$domtype[0]['name'],
            );
            array_push($mortsList, $map);
        }
        $InvestorInfo = D("InvestorInfo"); // 实例化InvestorInfo对象
        if (!$InvestorInfo->create($_POST,1)){
            // 如果创建失败 表示验证没有通过 输出错误提示信息
            $this->ajaxReturn(array('code'=>'error','info' => $InvestorInfo->getError()));//0错误，1成功
            exit();
        }
        
        $data['uid']=session('uid');
        $term_begin=I('term_begin','');
        $term_end=I('term_end','');
        if($term_begin=='' || $term_end==''){
           $this->ajaxReturn(array('code'=>'error','info' => '投资周期不能为空'));//0错误，1成功
            exit();
        }else if($term_begin>=$term_end){
            $this->ajaxReturn(array('code'=>'error','info' => '投资周期不正确'));//0错误，1成功
            exit();
        }
        $data['term_begin']=$term_begin;
        $data['term_end']=$term_end;
        $data['create_time']=date('y-m-d H:m:s',time());
        $data['descrp']=I('descrp','');
        $data['is_auto']=I('is_auto','');
        $id=$InvestorInfo->add($data);
        if($id>0){
            foreach ($mortsList as $mortCred){
                $mortCred['inve_id']=$id;
                $mortCred['createdate']=date('y-m-d H:m:s',time());
                M('InvesDomcate')->add($mortCred);
            }
        }
        if($data['is_auto']==2){
            $fl=D('CredFlow')->zidongtb($id,$term_begin,$term_end,session('uid'));
            if($fl>0){
                $this->ajaxReturn(array('code'=>'success','info' => '通过系统自动匹配，您已投资'.$fl.'元!'));//0错误，1成功
                exit();
            }else{
                $this->ajaxReturn(array('code'=>'success','info' => '投资信息发布成功!'));//0错误，1成功
                exit();
            }
        }else{
            $this->ajaxReturn(array('code'=>'success','info' => '投资信息发布成功!'));//0错误，1成功
            exit();
        }
    }
    /**
     * 我的投资记录列表
     */
    public function myinverflow(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $condi=' a.investuid='.session('uid');
        $status = I('status',0);
        is_numeric($status);
        if(!preg_match('/^\\d+$/',$status)) {
            $this->ajaxReturn(array('code'=>'error','info' => '参数有误！'));//0错误，1成功
            exit();
        }
        if($status!=0){
            $condi=$condi.' and a.status='.$status;
        }
       $dao=M();
       $list = $dao->query("SELECT a.id,a.money,a.persionnum,a.full_time,a.rpersionum,a.status,a.interest,a.expiredate,a.penalty,a.mangrate,a.rate,(SELECT b.username FROM dd_user b WHERE b.id=a.loanduid) AS username FROM dd_cred_flow a WHERE ".$condi);
       $this->assign('flowlist',$list);
       $this->assign('status',$status);
       $this->display('credit/inverflow');
    }
    
    
    
    /**
     * 我的借款记录列表
     */
    public function myloanflow(){
        if(session('uid')==null){
            $this->ajaxReturn(array('code'=>'error','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $condi=' a.loanduid='.session('uid');
        $status = I('status',0);
        is_numeric($status);
        if(!preg_match('/^\\d+$/',$status)) {
            $this->ajaxReturn(array('code'=>'error','info' => '参数有误！'));//0错误，1成功
            exit();
        }
        if($status!=0){
            $condi=$condi.' and a.status='.$status;
        }
        $dao=M();
        $list = $dao->query("SELECT a.id,a.money,a.persionnum,a.full_time,a.rpersionum,a.status,a.interest,a.expiredate,a.penalty,a.mangrate,a.rate,(SELECT b.username FROM dd_user b WHERE b.id=a.investuid) AS username FROM dd_cred_flow a WHERE ".$condi);
        $this->assign('flowlist',$list);
        $this->assign('status',$status);
        $this->display('credit/loanflow');
    }
    
    /**
     * 进行投资
     */
    public function toinver(){
        $id=I('id','');
        $money=I('money','');
        if(session('uid')==null){
            $this->ajaxReturn(array('status'=>'2','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        if($money==null || $money==0 || $money/100<=0){
            $this->ajaxReturn(array('status'=>'2','info' => '您的投资金额有误！'));//0错误，1成功
            exit();
        }
        $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.session('uid'))->select();
        if($creditmoney[0]['creditmoney']<=$money){
            $this->ajaxReturn(array('status'=>'2','info' => '您的理财宝资金不足，请先充值！'));//0错误，1成功
            exit();
        }
       $loadInfo = M('LoaderInfo')->find($id);
       if(empty($loadInfo)){
           $this->ajaxReturn(array('status'=>'2','info' => '此借款标不存在！'));//0错误，1成功
           exit();
       }
       if($loadInfo['uid']==session('uid')){
           $this->ajaxReturn(array('status'=>'2','info' => '您不能向您自己的借款标投资！'));//0错误，1成功
           exit();
       }
       $canMoney=$loadInfo['money']-$loadInfo['tovalue'];
       if($canMoney==0 || $canMoney<$money){
           $this->ajaxReturn(array('status'=>'2','info' => '投资资金大于此标剩余需求资金！'));//0错误，1成功
           exit();
       }
       $credFlow = M('CredFlow');
       $credate['loanduid']=$loadInfo['uid'];
       $credate['investuid']=session('uid');
       $credate['money']=$money;
       $credate['domtypeid']=$loadInfo['domaintypeid'];
       $tradeFee = M('TradeFee')->field('rate')->where('type=3')->select();
       
       $mortArr=array();
       if($loadInfo['term']-30<0){
           $credate['persionnum']=1;//还款期数
           array_push($mortArr, date("Y-m-d",strtotime($loadInfo['term']." day")).' 00:00:00');
           $lixi=$money*($loadInfo['rate']*0.01/360)*$loadInfo['term'];
           $lixi=(double)(sprintf("%.2f", $lixi));
           $credate['interest']=$lixi;//每期利息
           $credate['mangrate']=($tradeFee[0]['rate'])*0.01*$money;//管理费
       }else if($loadInfo['term']-30>=0){
           $credate['persionnum']=$loadInfo['term']/30;//还款期数
           $lixi=$money*($loadInfo['rate']*0.01/12); 
           $lixi=(double)(sprintf("%.2f", $lixi));
           $credate['interest']=$lixi;//每期利息
           $credate['mangrate']=(($tradeFee[0]['rate'])*0.01*$money)*$credate['persionnum'];//管理费
           for($i=1;$i<=$credate['persionnum'];$i++){
               $days=$loadInfo['term']*$i;
               array_push($mortArr, date("Y-m-d",strtotime($days." day")).' 00:00:00');
           }
       }
       
       $credate['rpersionum']=0;//已还期数
       $credate['penalty']=0;//罚息
       $credate['createdate']=date('y-m-d H:m:s',time());
       $credate['rate']=$loadInfo['rate'];//rate
       $credate['loanid']=$loadInfo['id'];
       $credate['status']=4;
       $credate['cred_code']=$loadInfo['cred_code'];
        /**
         * 到此满标
         */
        if($canMoney==$money){
            $credate['full_time']=date('y-m-d H:m:s',time());
            $credate['status']=1;
           $danqianflow= $credFlow->add($credate);
            /**
             * 批量修改抵押域名状态和授信额度
             * @var unknown
             */
            $loanDomainList = M('LoanDomains')->field('domainid')->where('loanid='.$loadInfo['id'])->select();
            $crefowData['uid']=$loadInfo['uid'];
            $credflowDomian=M('CredflowDomian');
            foreach ($loanDomainList as $loanDomain){//修改域名从投标中变为抵押状态
                M('UserDomains')->where('id='.$loanDomain['domainid'])->setField(array('is_mortage'=>2));
                $crefowData['domainid']=$loanDomain['domainid'];
                $crefowData['credit']=$loadInfo['credmoney'];
                $crefowData['cred_code']=$loadInfo['cred_code'];
                $credflowDomian->add($crefowData);//添加借款域名授信表
            }
            //修改借款标状态为已满标
            M('LoaderInfo')->where('id='.$id)->setField(array('tovalue'=>$loadInfo['money'],'status'=>2,'full_time'=>date('y-m-d H:m:s',time())));
            //修改借款人资金账户，加值
            M('UserAssets')->where('uid='.$loadInfo['uid'])->setInc('avail_money',$loadInfo['money']);
            M('UserAssets')->where('uid='.$loadInfo['uid'])->setInc('present_money',$loadInfo['money']);
            $UserCaptdetail=M('UserCaptdetail');
            $capdet['uid']=$loadInfo['uid'];
            $capdet['flow_money']=$money;
            $capdet['tran_type']=1;
            $capdet['tran_income']=4;
            $capdet['createdate']=date('y-m-d H:m:s',time());
            $UserCaptdetail->add($capdet);
            //遍历处理投资人流水
            $credlist = M("CredFlow")->field('id,investuid,money')->where("cred_code='".$loadInfo['cred_code']."'")->select();//获得所有投递此标的投资流水
            foreach ($credlist as $cred){
                $expiredate=date("Y-m-d",strtotime($loadInfo['term']." day")).' 00:00:00';
                M("CredFlow")->where('id='.$cred['id'])->setField(array('status'=>1,'expiredate'=>$expiredate,'full_time'=>date('y-m-d H:m:s',time())));
                $repaymentDa['cred_flowid']=$cred['id'];
                $repaymentDa['loaduid']=$loadInfo['uid'];
                $repaymentDa['investuid']=$cred['investuid'];
                $repaymentDa['createdate']=date('y-m-d H:m:s',time());
                $repaymentDa['is_yq']=1;
                $repaymentDa['cred_code']=$loadInfo['cred_code'];
                for($j=1;$j<=count($mortArr);$j++){
                    $repaymentDa['stage']=$j;
                    $repaymentDa['repaydate']=$mortArr[$j-1];
                    M('RepaymentFlow')->add($repaymentDa);
                }
                /**
                 * 投资人账户操作
                 * 
                 */
                if($cred['id']!=$danqianflow){//从冻结的资金里扣除
                    M('UserAssets')->where('uid='.$cred['investuid'])->setDec('locked_money',$cred['money']);
                }else{
                    M('UserAssets')->where('uid='.$cred['investuid'])->setDec('creditmoney',$cred['money']);
                }
                $capdet['uid']=$cred['investuid'];
                $capdet['flow_money']=$cred['money'];
                $capdet['tran_type']=2;
                $capdet['tran_income']=4;
                $capdet['createdate']=date('y-m-d H:m:s',time());
                $UserCaptdetail->add($capdet);
            }
            $this->ajaxReturn(array('status'=>'1','info' => '投资已提交，项目已完成!'));
            exit();
        }else{//未满标
            
            $credate['status']=4;
            $credFlow->add($credate);
            /**
             * 修改该笔借款项目实际借款金额
             */
            M('LoaderInfo')->where('id='.$loadInfo['id'])->setInc('tovalue',$money);
            
            /**
             * 投资人账户操作-减少理财宝到锁定资金账户
             *
             */
            M('UserAssets')->where('uid='.session('uid'))->setDec('creditmoney',$money);
            M('UserAssets')->where('uid='.session('uid'))->setInc('locked_money',$money);
            $this->ajaxReturn(array('status'=>'1','info' => '投资已提交，等待借款项目满表!'));
            exit();
        }
    }
    
    /**
     * 进行借款
     */
    public function toloan(){
        //'id':id,'money':$('#inputAmount').val(),'domtype':cateid,'term':$("#termMonth").val()
        $id=I('id','');
        $money=I('money','');
        $domtype=I('domtype','');
        $term=I('term','');
        if(session('uid')==null){
            $this->ajaxReturn(array('status'=>'2','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        if($money==null || $money==0){
            $this->ajaxReturn(array('status'=>'2','info' => '您的投资金额有误！'));//0错误，1成功
            exit();
        }
        if($id==null || $domtype=='' || $term==''){
            $this->ajaxReturn(array('status'=>'2','info' => '请求参数错误！'));//0错误，1成功
            exit();
        }
        
        $investInfo = M('InvestorInfo')->find($id);
        if(empty($investInfo)){
            $this->ajaxReturn(array('status'=>'2','info' => '此投资标不存在！'));//0错误，1成功
            exit();
        }
        if($investInfo['uid']==session('uid')){
            $this->ajaxReturn(array('status'=>'2','info' => '您不能向您自己的标借款！'));//0错误，1成功
            exit();
        }
        $creditmoney=M('UserAssets')->field('creditmoney')->where('uid='.$investInfo['uid'])->select();
        if($creditmoney[0]['creditmoney']<$money){
            $this->ajaxReturn(array('status'=>'2','info' => '借款金额超过了投资人理财宝余额！'));//0错误，1成功
            exit();
        }
        if($investInfo['term_begin']>$term || $investInfo['term_end']<$term){
            $this->ajaxReturn(array('status'=>'2','info' => '选择的借款周期必须在'.$investInfo['term_begin'].'天到'.$investInfo['term_end'].'之间'));//0错误，1成功
            exit();
        }
        
        $invecate=M('InvesDomcate')->field('credit,rate,domtypeid')->where('inve_id='.$investInfo['id'].' and domtypeid='.$domtype)->select();
        $invecate=$invecate[0];
        if(empty($invecate)){
            $this->ajaxReturn(array('status'=>'2','info' => '此投资标对应域名类型授信不存在！'));//0错误，1成功
            exit();
        }
        if(($money%$invecate['credit'])!=0){
            $this->ajaxReturn(array('status'=>'2','info' => '借款金额必须是授信额度'.$invecate['credit'].'的整数倍！'));//0错误，1成功
            exit();
        }
        $domNum=(int)($money/$invecate['credit']);//需要质押的域名数量
        
        $domain['uid']=session('uid');
        $domain['is_mortage']=1;
        $domain['check_status']=3;
        $domain['trans_status']=1;
        $domain['domain_typeid']=$domtype;
        
        $domainList=M('UserDomains')->field('id')->where($domain)->limit($domNum)->select();
        if(count($domainList)<$domNum){
            $this->ajaxReturn(array('status'=>'2','info' => '您可抵押的此类域名不足'.$domNum.'个,暂无法借款！'));//0错误，1成功
            exit();
        }
        $credFlow = M('CredFlow');
        $credate['loanduid']=session('uid');
        $credate['investuid']=$investInfo['uid'];
        $credate['money']=$money;
        $credate['domtypeid']=$invecate['domtypeid'];
        $tradeFee = M('TradeFee')->field('rate')->where('type=3')->select();
         
        $mortArr=array();
        if($term-30<0){
            $credate['persionnum']=1;//还款期数
            array_push($mortArr, date("Y-m-d",strtotime($term." day")).' 00:00:00');
            $lixi=$money*($invecate['rate']*0.01/360)*$term;
            $lixi=(double)(sprintf("%.2f", $lixi));
            $credate['interest']=$lixi;//每期利息
            $credate['mangrate']=($tradeFee[0]['rate'])*0.01*$money;//管理费
        }else if($term-30>=0){
            $credate['persionnum']=$term/30;//还款期数
            $lixi=$money*($invecate['rate']*0.01/12);
            $lixi=(double)(sprintf("%.2f", $lixi));
            $credate['interest']=$lixi;//每期利息
            $credate['mangrate']=(($tradeFee[0]['rate'])*0.01*$money)*$credate['persionnum'];//管理费
            for($i=1;$i<=$credate['persionnum'];$i++){
                $days=30*$i;
                array_push($mortArr, date("Y-m-d",strtotime($days." day")).' 00:00:00');
            }
        }
         
        $credate['rpersionum']=0;//已还期数
        $credate['penalty']=0;//罚息
        $credate['createdate']=date('y-m-d H:m:s',time());
        $credate['rate']=$invecate['rate'];//rate
        $credate['investid']=$investInfo['id'];
        $credate['cred_code']=D('CredFlow')->create_uuid();
        /**
         * 到此满标
         */
        $credate['full_time']=date('y-m-d H:m:s',time());
        $credate['status']=1;
        $credate['expiredate']=date("Y-m-d",strtotime($term." day")).' 00:00:00';
        $credflowid=$credFlow->add($credate);
        /**
         * 批量修改抵押域名状态和授信额度
         * @var unknown
        */
        $crefowData['uid']=session('uid');
        $credflowDomian=M('CredflowDomian');
        $crefowData['cred_code']=$credate['cred_code'];
        foreach ($domainList as $dom){//修改域名从投标中变为抵押状态
            M('UserDomains')->where('id='.$dom['id'])->setField(array('is_mortage'=>2));
            $crefowData['domainid']=$dom['id'];
            $crefowData['credit']=$invecate['credit'];
            $credflowDomian->add($crefowData);//添加借款域名授信表
        }
        //修改借款人资金账户，加值
        M('UserAssets')->where('uid='.session('uid'))->setInc('avail_money',$money);
        M('UserAssets')->where('uid='.session('uid'))->setInc('present_money',$money);
        
        $UserCaptdetail=M('UserCaptdetail');
        $capdet['uid']=session('uid');
        $capdet['flow_money']=$money;
        $capdet['tran_type']=1;
        $capdet['tran_income']=4;
        $capdet['createdate']=date('y-m-d H:m:s',time());
        $UserCaptdetail->add($capdet);
        /**
         * 插入还款期标
         */
        $repaymentDa['cred_flowid']=$credflowid;
        $repaymentDa['loaduid']=session('uid');
        $repaymentDa['investuid']=$investInfo['uid'];
        $repaymentDa['createdate']=date('y-m-d H:m:s',time());
        $repaymentDa['is_yq']=1;
        $repaymentDa['cred_code']=$credate['cred_code'];
        for($j=1;$j<=count($mortArr);$j++){
            $repaymentDa['stage']=$j;
            $repaymentDa['repaydate']=$mortArr[$j-1];
            M('RepaymentFlow')->add($repaymentDa);
        }
        M('UserAssets')->where('uid='.$investInfo['uid'])->setDec('creditmoney',$money);
        $capdet['uid']=$investInfo['uid'];
        $capdet['flow_money']=$money;
        $capdet['tran_type']=2;
        $capdet['tran_income']=4;
        $capdet['createdate']=date('y-m-d H:m:s',time());
        $UserCaptdetail->add($capdet);
        M('InvestorInfo')->where('id='.$investInfo['id'])->setInc('tovalue',$money);
        $this->ajaxReturn(array('status'=>'1','info' =>'您的借款已成功，请按期还款!'));
        exit();
    }
    
    /**
     * 修改借款人借款标状态
     */
    public function updaisopenloader(){
        if(session('uid')==null){
            $this->ajaxReturn(array('status'=>'2','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $id=I('id','');
        if($id==''){
            $this->ajaxReturn(array('status'=>'2','info' => '参数错误！'));//0错误，1成功
            exit();
        }
        $loaderArr = M('LoaderInfo')->where('uid='.session('uid').' and id='.$id)->field('id,is_open')->select();
        if(empty($loaderArr)){
            $this->ajaxReturn(array('status'=>'2','info' => '此借款标不存在或不是发标本人操作！'));//0错误，1成功
            exit();
        }
        $loader=$loaderArr[0];
        if($loader['is_open']==0){
            M('LoaderInfo')->where('id='.$id)->setField(array('is_open'=>1));
        }else{
            M('LoaderInfo')->where('id='.$id)->setField(array('is_open'=>0));
        }
        $this->ajaxReturn(array('status'=>'0','info' => '操作成功！'));//0错误，1成功
        exit();
    }
    
    
    /**
     * 修改投资人投资标状态
     */
    public function updaisopeninvest(){
        if(session('uid')==null){
            $this->ajaxReturn(array('status'=>'2','info' => '请选去登录！'));//0错误，1成功
            exit();
        }
        $id=I('id','');
        if($id==''){
            $this->ajaxReturn(array('status'=>'2','info' => '参数错误！'));//0错误，1成功
            exit();
        }
        $investArr = M('InvesDomcate')->where('id='.$id)->field('id,is_open')->select();
        if(empty($investArr)){
            $this->ajaxReturn(array('status'=>'2','info' => '此投资标不存在或不是发标本人操作！'));//0错误，1成功
            exit();
        }
        $invest=$investArr[0];
        if($invest['is_open']==0){
            M('InvesDomcate')->where('id='.$id)->setField(array('is_open'=>1));
        }else{
            M('InvesDomcate')->where('id='.$id)->setField(array('is_open'=>0));
        }
        $this->ajaxReturn(array('status'=>'0','info' => '操作成功！'));//0错误，1成功
        exit();
    }
}